package com.wlyy.starter.mybatis;

import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;

import java.util.List;
import java.util.stream.Collectors;

import static com.baomidou.mybatisplus.core.toolkit.StringPool.COMMA;
import static com.baomidou.mybatisplus.core.toolkit.StringPool.EMPTY;
import static com.baomidou.mybatisplus.core.toolkit.StringPool.HASH_LEFT_BRACE;
import static com.baomidou.mybatisplus.core.toolkit.StringPool.RIGHT_BRACE;
import static com.baomidou.mybatisplus.core.toolkit.StringPool.SPACE;

/**
 * 生成各段sql片段
 */
public class SQLUtil {

    //*_**,**_*,*_*
    public static String getAllColumn(TableInfo tableInfo) {
        List<TableFieldInfo> fieldList = tableInfo.getFieldList();
        String cs = fieldList.stream().map(TableFieldInfo::getColumn).collect(Collectors.joining(","));
        if (tableInfo.havePK()) {
            String keyColumn = tableInfo.getKeyColumn();
            cs = keyColumn + COMMA + cs;
        }
        return cs;
    }
    /**
     * <code>
     *      <if ...>product_id = VALUES(product_id)</if>
     * </code>
     */
    public static String getAllSetValues(TableInfo tableInfo) {
        String startTemp = "<if test=\"%s != null\"> %s = VALUES(%s) </if>";
        String temp = "<if test=\"%s != null\"> ,%s = VALUES(%s) </if>";
        String sql = EMPTY;
        List<TableFieldInfo> fieldList = tableInfo.getFieldList();
        for (int i = 0; i < fieldList.size(); i++) {
            TableFieldInfo field = fieldList.get(i);
            String column = field.getColumn();
            String property = field.getProperty();
            if (i == 0) {
                sql += String.format(startTemp, property, column, column);
            } else {
                sql += String.format(temp, property, column, column);
            }
        }
        return sql;
    }

    //#{et.id},**,#{et.**}
    public static String getAllField(TableInfo tableInfo, String pre) {
        List<TableFieldInfo> fieldList = tableInfo.getFieldList();
        String fs = fieldList.stream().map(f -> {
            return SQLUtil.formatFiled(f, pre);
        }).collect(Collectors.joining(","));
        if (tableInfo.havePK()) {
            fs = formatFiled(tableInfo.getKeyProperty(), pre) + COMMA + fs;
        }
        return fs;
    }

    // #{et.***}
    public static String formatFiled(TableFieldInfo fieldInfo, String pre) {
        return formatFiled(fieldInfo.getProperty(), pre);
    }

    public static String formatFiled(String fieldName, String pre) {
        return SPACE + HASH_LEFT_BRACE + pre + fieldName + RIGHT_BRACE + SPACE;
    }
}
